/**
 * 
 */
package org.alipay4j.http;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.alipay4j.Alipay;
import org.alipay4j.AlipayException;
import org.alipay4j.util.DateUtil;
import org.alipay4j.util.MapUtil;
import org.alipay4j.util.ObjectHelper;

import com.alibaba.fastjson.JSONObject;

/**
 * 支付宝请求客户端
 * @author 贺亮
 *
 */
public class AlipayHttpsClient implements java.io.Serializable {
	/**  */
	private static final long serialVersionUID = -6080478012364136036L;
	/** 配置管理 */
	private Alipay alipay;
	
	public AlipayHttpsClient() {
		super();
	}
	
	public AlipayHttpsClient(Alipay alipay) {
		super();
		this.alipay = alipay;
	}
	
	/**
	 * 带参数请求
	 * @param content
	 * @return
	 */
	public Response post(Map<String, String> content) {
		Map<String, String> common = getAlipayParam();
		if(ObjectHelper.isNotEmpty(content)) {
			common.putAll(content);
		}
		//获得签名
		common.put("sign", getSign(common));
		//请求
		Response response = null;
		try {
			response = new HttpsClient().post(this.alipay.getAlipayConfig().getAlipayGateway(), common);
		} catch (AlipayException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	* @Title: 带参数请求 BizContent
	* @Description: 带参数请求 BizContent 
	* @author heliang
	* @param content b报文体
	* @return  Response
	 */
	public Response postBizContent(Map<String, String> content) {
        Map<String, String> common = getAlipayParam();
        //方法名操作
        String method = content.get("method");
        content.remove("method");
        common.put("method", method);
        //设置比biz_content报文体
        common.put("biz_content", JSONObject.toJSONString(content));
        //获得签名
        common.put("sign", getSign(common));
        //请求
        Response response = null;
        try {
            response = new HttpsClient().post(this.alipay.getAlipayConfig().getAlipayGateway(), common);
        } catch (AlipayException e) {
            e.printStackTrace();
        }
        return response;
    }
	
	public Map<String, String> getAlipayParam() {
		Map<String, String> param = new HashMap<String, String>();
		param.put("app_id", this.alipay.getAppId());//支付宝分配给开发者的应用ID
		param.put("format", "JSON");//仅支持JSON
		param.put("charset", "utf-8");//请求使用的编码格式，如utf-8,gbk,gb2312等
		param.put("sign_type", "RSA2");//商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
		param.put("timestamp", DateUtil.format(new Date(), DateUtil.FormatType.DAYTIME));//发送请求的时间，格式"yyyy-MM-dd HH:mm:ss"
		param.put("version", "1.0");//调用的接口版本，固定为：1.0
		return param;
	}
	
	private String getSign(Map<String, String> param) {
		//排序
		param = MapUtil.sortAsc(param);
		//拼接
		String rsaContent = getSignStr(param);
		//公钥加密
		String sign = null;
		try {
			sign = SignatureHelper.rsaSign(rsaContent, alipay.getAlipayConfig().getAppPriKey());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sign;
	}
	/**
	 * 待验签字符串
	 * @param url
	 * @param body
	 * @return
	 */
	public String getSignStr(Map<String, String> body) {
    	StringBuffer buffer = new StringBuffer("");
        for (Entry<String, String> entry : body.entrySet()) {
            try {
                if (ObjectHelper.isEmpty(entry.getValue())) {
                    continue;
                }
                //中文转码
                String valStr = entry.getValue().toString().trim();
                buffer.append(entry.getKey()+"="+valStr+"&");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 去掉最后一个字符"&"
        buffer.deleteCharAt(buffer.length() - 1);
        System.out.println("待验签:\n" + buffer.toString() + "\n");
        return buffer.toString();
    }
}
